//
//  SMSCodeViewController.swift
//  IDF
//
//  Created by 陈徐挺 on 23/03/2018.
//  Copyright © 2018 Jesse.chen. All rights reserved.
//

import UIKit
import SwiftyTimer
import SVProgressHUD
import YYCache

class SMSCodeViewController: BaseViewController {

    @IBOutlet weak var tipsTF: UILabel!
    @IBOutlet weak var pwdTF: UITextField!
    @IBOutlet weak var smsCodeTF: UITextField!
    @IBOutlet weak var resendBtn: UIButton!
    @IBOutlet weak var timeLabel: UILabel!
    var timer: Timer!
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "Set the password"
        // Do any additional setup after loading the view.
        tipsTF.text = "The Verification code has been sent to " + appUser.phone
        setTimer()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func sndSMS(_ sender: UIButton) {
        setTimer()
    }
    
    @IBAction func signUpBtn(_ sender: UIButton) {
        SVProgressHUD.show()
        appUser.password = pwdTF.text
        appUser.register(smsCodeTF.text!).then{ _ -> Void in
            let cache = YYCache(name: "appcache")
            cache?.setObject(appUser, forKey: "appUser")
            appLogined = true
            initAliyun()
            if registrationId != "" {
                syncUserRegistration(registrationId)
            }
            nowNavgationController.popToRootViewController(animated: true
            )
        }
    }
    
    
    func setTimer() {
        resendBtn.isEnabled = false
        var seconds = 60
        timeLabel.text = "\(seconds)s"
        timer = Timer.every(1.seconds) { [unowned self] (timer: Timer) in
            if seconds == 0 {
                timer.invalidate()
                self.timeLabel.text = "Resend"
                self.resendBtn.isEnabled = true
            } else {
                seconds -= 1
                self.timeLabel.text = "\(seconds)s"
            }
        }
    }
    
    deinit {
        if let t = timer {
            t.invalidate()
        }
       
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
